package org.wicket.jbpm.login;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.value.ValueMap;
import org.wicket.jbpm.WicketJBPMSession;
import org.wicket.jbpm.model.User;
import org.wicket.jbpm.page.IndexPage;
import org.wicket.jbpm.page.admin.JBPMAdminPage;
import org.wicket.jbpm.service.user.UserService;
import org.wicket.jbpm.utils.UserRole;

/**
 * @author Emmanuel Nollase - emanux
 * created: May 18, 2009 - 10:25:32 PM
 */
public class WicketJBPMLogin extends WebPage {

	@SpringBean private UserService userService; 
	
	private final ValueMap prop = new ValueMap();
	
	public WicketJBPMLogin() {
		
		final FeedbackPanel feedback = new FeedbackPanel("feedback");
		add(feedback.setOutputMarkupId(true));
		
		final Form form = new StatelessForm("login");
		add(form);
		
		final RequiredTextField username = new RequiredTextField("username", new PropertyModel(prop,"username"));
		form.add(username);
		final PasswordTextField password = new PasswordTextField("password", new PropertyModel(prop,"password"));
		form.add(password);
		
		final IndicatingAjaxButton submit = new IndicatingAjaxButton("submit", form){
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				final String username = prop.getString("username");
				final String password =  prop.getString("password");
				boolean _check = userService.checkUser(username, password);
				if(_check)
				{
					final User user = userService.loadUser(username, password);
					WicketJBPMSession.get().setUser(user);
					
					if(StringUtils.equals(user.getGroup().getDscp(), UserRole.ADMIN))
					{
					    setResponsePage(JBPMAdminPage.class);
					}
					else
					{
					    setResponsePage(IndexPage.class);
					}
				}
				feedback.error("User does not exist.");
				target.addComponent(feedback);
			}
			@Override
			protected void onError(AjaxRequestTarget target, Form form) {
				target.addComponent(feedback);
				super.onError(target, form);
			}
		};
		
		form.add(submit);
	}
}

